package com.suxii.frpclient.thread;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.suxii.frpclient.message.ServiceStateMessage;
import com.suxii.frpclient.message.TaskRunningMessage;
import com.suxii.frpclient.utils.FileUtil;
import com.suxii.frpclient.utils.RxBus;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FrpThread extends Thread{
    private final Context context;
    private Process process;

    public FrpThread(Context context) {
        this.context = context;
    }

    @Override
    public void run() {
//        FileUtil.initConfigFile(context);
        try {
            String command = getCommand();
            executeCommand(command);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private volatile boolean running = true;

    private String getCommand() throws PackageManager.NameNotFoundException {
        ApplicationInfo info = context.getPackageManager().getApplicationInfo(
                context.getPackageName(),
                PackageManager.GET_SHARED_LIBRARY_FILES
        );

        String filename = "libfrpc.so";
        String path = context.getFilesDir().getPath() + "/frpc.toml";
        return info.nativeLibraryDir + "/" + filename + " -c "+ path;
    }


 /*   private void runCommand(String command){
        File workDir = context.getFilesDir();

        ProcessBuilder pb = new ProcessBuilder(command.split(" "));
        pb.directory(workDir);
        Process process = null;
        try {
            process = pb.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        InputStream stdout = process.getInputStream();
        InputStream stderr = process.getErrorStream();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(stdout))){
            String s;
            while (running && (s = br.readLine()) != null){
                Log.i("stdout",s);
                RxBus.getInstance().post(new TaskRunningMessage(true,s));
            }
        } catch (Exception e) {
            RxBus.getInstance().post(new TaskRunningMessage(false,e.getMessage()));
        }
    }
*/
    public void executeCommand(String command) {
        File workDir = context.getFilesDir();

        ProcessBuilder pb = new ProcessBuilder(command.split(" "));
        pb.directory(workDir);
        try {
            process = pb.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 获取标准输出和标准错误流
        InputStream stdout = process.getInputStream();
        InputStream stderr = process.getErrorStream();

        // 创建并启动两个线程来处理标准输出和标准错误流
        Thread stdoutThread = new Thread(() -> {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(stdout))) {
                String line;
                while (running && (line = br.readLine()) != null) {
                    Log.i("stdout", line);
                    RxBus.getInstance().post(new TaskRunningMessage(true, line));
                }
            } catch (Exception e) {
                RxBus.getInstance().post(new TaskRunningMessage(false, e.getMessage()));
            }
        });

        Thread stderrThread = new Thread(() -> {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(stderr))) {
                String line;
                while (running && (line = br.readLine()) != null) {
                    Log.e("stderr", line);
                    RxBus.getInstance().post(new TaskRunningMessage(false, line));
                }
            } catch (Exception e) {
                RxBus.getInstance().post(new TaskRunningMessage(false, e.getMessage()));
            }
        });

        stdoutThread.start();
        stderrThread.start();

        // 等待进程结束
        int exitCode;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
            throw new RuntimeException(e);
        } finally {
            running = false; // 停止读取流的线程
        }

        // 根据退出码判断命令是否成功
        if (exitCode == 0) {
            RxBus.getInstance().post(new TaskRunningMessage(true, "Command executed successfully"));
        } else {
            RxBus.getInstance().post(new TaskRunningMessage(false, "Command failed with exit code: " + exitCode));
        }
    }


    public void stopThread(){
        running = false;
        if(process != null) {
            process.destroy();
        }
    }

}
